package com.tonann.web.api;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.weixin.config.WxMaProperties;
import com.tonann.weixin.model.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/sub")
@Api(value = "SubscribeMessage", tags = "小程序订阅消息")
public class SubscribeMessageApi {

    private final WxMaProperties wxMaProperties;

    @ApiOperation(value = "开发者消息推送")
    @GetMapping("/message")
    public String subscribeMessage(String signature, Long timestamp, String nonce, String echostr) {
        System.out.println(signature + "=======" + timestamp + "=====" + nonce + "====" + echostr);
        String token = "045d3b9a082459d35b6729735725ef92";
        return echostr;
    }

    //发送消息
    @PostMapping("/addsenddata")
    public AjaxResult sendMessage(@RequestBody SubscribeMessage subscribeMessage) {
        String ACCESS_TOKEN = null;
        // 微信小程序ID
        String appid = "wx6e420f8197aa9b3d";
        Long startTime = WXAccessToken.getInstance().getGetTime();
        if (startTime == null || System.currentTimeMillis() / 1000 - startTime > 0) {
            JSONObject jsonObject = this.getToken(appid);
            Integer expiresTime = jsonObject.get("expires_in", Integer.class);
            String accessToken = jsonObject.get("access_token", String.class);
            WXAccessToken.getInstance().setWxAccessToken(accessToken);
            WXAccessToken.getInstance().setGetTime(System.currentTimeMillis() / 1000 + expiresTime);
        }
        ACCESS_TOKEN = WXAccessToken.getInstance().getAccessToken();
        // 根据小程序穿过来的code想这个url发送请求
        OuterData outerData = new OuterData();
//        outerData.setAccess_token(ACCESS_TOKEN);
        outerData.setLang("zh_CN");
        outerData.setMiniprogram_state("formal");
        outerData.setPage("pages/home/index");
        outerData.setTo_openid_list(new String[]{subscribeMessage.getOpenId()});
        outerData.setTemplate_id("y5v6VYlNXIv-yP7BIKjmwiG2zF8R3wxd0F_Tr9HIf1s");
        outerData.setSn(subscribeMessage.getSn());
        outerData.setModel_id(subscribeMessage.getModel_id());
        MsgData msgData = new MsgData();
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        month += 1;
        int day = calendar.get(Calendar.DATE);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        int s = calendar.get(Calendar.SECOND);
        String dateTime = calendar.get(Calendar.YEAR) + "-" + month + "-" + calendar.get(Calendar.DATE) + " " + (h > 9 ? h : "0" + h) + ":" + (m > 9 ? m : "0" + m) + ":" + (s > 9 ? s : "0" + s);
//        msgData.setDate1(new InnerData(dateTime));
//        msgData.setThing3(new InnerData("大学城D1"));
//        msgData.setThing6(new InnerData("烟雾报警"));
//        msgData.setThing5(new InnerData("打印机没墨"));
//        msgData.setPhrase17(new InnerData("紧急"));
        msgData.setTime1(new InnerData(dateTime));
        msgData.setEnum_string2(new InnerData("过滤器报警"));
        msgData.setEnum_string3(new InnerData("紧急"));
        msgData.setEnum_string4(new InnerData("新风设备发生告警，请及时处理"));
        outerData.setData(msgData);
//        outerData.setTemplate_id("AKxwPdaPQKv7HfEJP1UPmNYLDNT1q0VDM4AX00xAuNQ");
//        outerData.setTouser(subscribeMessage.getOpenId());

        String _jsonData = JSON.toJSONString(outerData);
        System.out.println("sendMesg传入参数" + _jsonData);

//        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+ACCESS_TOKEN;
        String url = "https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token=" + ACCESS_TOKEN;
        HttpResponse response = HttpRequest.post(url)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
//                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .header(Header.CONTENT_TYPE, "application/json")
                .body(_jsonData)
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {

        }
        System.out.println("jsonObject____" + response.body());
        // 我们需要的openid，在一个小程序中，openid是唯一的
        return AjaxResult.success();
    }

    public JSONObject getToken(String appId) {
        String result = null;
        String APPID = appId;
        String APPSECRET = null;
        List<WxMaProperties.Config> configs = wxMaProperties.getConfigs();
        if (configs != null) {
            for (WxMaProperties.Config config : configs) {
                String app = config.getAppId();
                if (app.equals(appId)) {
                    APPSECRET = config.getSecret();
                }
            }
        }
        if (APPSECRET == null) {
            return null;
        }
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;
        HttpResponse response = HttpRequest.get(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        return JSONUtil.parseObj(result);
    }
}
